package com.wxj.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxj.edu.entity.Subject;
import com.wxj.edu.entity.excel.SubjectData;
import com.wxj.edu.entity.subject.OneSubject;
import com.wxj.edu.entity.subject.TwoSubject;
import com.wxj.edu.listener.SubjectExcelListener;
import com.wxj.edu.mapper.SubjectMapper;
import com.wxj.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wxj.servicebase.exceptionHandler.BaseException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author wxj
 * @since 2021-03-08
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    //添加课程分类
    @Override
    public void addSubject(MultipartFile file,SubjectService subjectService) {
        try {
            //1 获取文件输入流
            InputStream in = file.getInputStream();
            // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(20002, "添加课程分类失败");
        }


    }

    //课程分类列表（树形）
    @Override
    public List<OneSubject> getAllSubject() {

        //查询所有一级分类
        QueryWrapper<Subject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<Subject> oneSubject = baseMapper.selectList(wrapperOne);

        //查询所有二级分类
        QueryWrapper<Subject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0"); //eq是等于，ne是不等于
        List<Subject> twoSubject = baseMapper.selectList(wrapperTwo);

        //创建list集合，用于存储最终封装数据
        List<OneSubject> finalSubjectList = new ArrayList<>();

        //封装所有一级分类
        for (Subject subject : oneSubject) {
            OneSubject one = new OneSubject();
//            one.setId(subject.getId());
//            one.setTitle(subject.getTitle());
            BeanUtils.copyProperties(subject,one);
            finalSubjectList.add(one);

            //封装所有二级分类
            List<TwoSubject> twoFinalSubjectList = new ArrayList<>();
            for (Subject secondSubject : twoSubject) {
                if (secondSubject.getParentId().equals(subject.getId())) {
                    TwoSubject two = new TwoSubject();
                    BeanUtils.copyProperties(secondSubject,two);
                    twoFinalSubjectList.add(two);
                }
            }
            one.setChildren(twoFinalSubjectList);
        }
        return finalSubjectList;
    }


}
